﻿using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace DimensionsHelper.Client.Converters;

public class FontSizePtConverter : IValueConverter
{
    private static double _dpi = 96;

    public double MinValue { get; set; } = 6;

    public double MaxValue { get; set; } = 72;


    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is double d && d >= MinValue && d <= MaxValue)
        {
            return d * _dpi / 72;
        }

        return MinValue * _dpi / 72;
    }


    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is double d)
        {
            return d * 72 / _dpi;
        }

        if (value is string str && str.EndsWith("pt") &&
            double.TryParse(str.AsSpan(0, str.Length - 2), out double dNum))
        {
            return dNum * 72 / _dpi;
        }

        return MinValue * 72 / _dpi;
    }


    public static void SetDpiFromVisual(Visual visual)
    {
        PresentationSource? source = PresentationSource.FromVisual(visual);

        if (source?.CompositionTarget != null)
        {
            _dpi = 96.0 * source.CompositionTarget.TransformToDevice.M11;
        }
    }
}
